package com.lcy.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.lcy.mapper.OjProblemSubmitMapper;
import com.lcy.model.entity.OjProblemSubmit;
import com.lcy.model.vo.HeatmapDataVo;
import com.lcy.security.utils.SecurityHelper;
import com.lcy.service.HeatmapService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lcy.model.entity.table.OjProblemSubmitTableDef.OJ_PROBLEM_SUBMIT;

/**
 * 热力图服务实现
 *
 * @author zhang.rx
 */
@Service
@RequiredArgsConstructor
public class HeatmapServiceImpl implements HeatmapService {

    private final OjProblemSubmitMapper problemSubmitMapper;

    @Override
    public List<HeatmapDataVo> getUserSubmissionHeatmap(Integer days) {
        // 默认获取前55天的数据
        int daysToFetch = days != null ? days : 55;

        // 获取当前用户ID
        Long userId = SecurityHelper.getUser().getId();

        // 计算开始日期和结束日期
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(daysToFetch);

        // 查询该用户在指定日期范围内的所有提交记录
        List<OjProblemSubmit> submits = QueryChain.of(problemSubmitMapper)
                .where(OJ_PROBLEM_SUBMIT.USER_ID.eq(userId))
                .and(OJ_PROBLEM_SUBMIT.CREATE_TIME.between(
                        startDate.atStartOfDay(),
                        endDate.plusDays(1).atStartOfDay())
                )
                .select()
                .list();

        // 按日期统计提交次数
        Map<String, Integer> submissionCountByDate = new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 初始化日期范围内的所有日期，默认提交次数为0
        for (int i = 0; i < daysToFetch; i++) {
            LocalDate date = startDate.plusDays(i);
            submissionCountByDate.put(date.format(formatter), 0);
        }

        // 统计提交次数
        for (OjProblemSubmit submit : submits) {
            String submitDate = submit.getCreateTime().toLocalDate().format(formatter);
            submissionCountByDate.put(submitDate, submissionCountByDate.getOrDefault(submitDate, 0) + 1);
        }

        // 构建结果
        List<HeatmapDataVo> result = new ArrayList<>();
        submissionCountByDate.forEach((date, count) ->
                result.add(new HeatmapDataVo(date, count))
        );

        return result;
    }
}